
//
//  UserAccountViewModel.swift
//  Weibo
//
//  Created by 李亚乐 on 15/12/9.
//  Copyright © 2015年 李亚乐. All rights reserved.
//

import Foundation

// MARK: - 用户账号视图模型
class UserAccountViewModel {
    
    /// 单例
    static let sharedUserAccount = UserAccountViewModel()
    
    /// 用户账号
    var account: UserAccount?
    /// 令牌
    var Token: String? {
        if !isExpired {
            return account?.access_token
        }
        return nil
    }
    /// 用户登录标记
    var userLogon: Bool {
        return !isExpired && account?.access_token != nil
    }
    /// 用户头像地址
    var avatarUrl: NSURL {
        return NSURL(string: account?.avatarLarge ?? "")!
    }
    
    /// 本地账号存储地址
    var accountPath: String {
        let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true).last!
        return (path as NSString).stringByAppendingPathComponent("account.plist")
    }
    
    /// 过期标记
    private var isExpired: Bool {
        if account?.expireDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            
            return true
        }
        return false
    }
    
    //MARK:-  重写构造方法
    ///
    /// - returns: 当前对象
    private init () {
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        if isExpired {
            print("过期了")
            account = nil
        }
    }
}

// MARK: - 用户相关的网络方法
extension UserAccountViewModel {
    
    /// 加载用户令牌
    ///
    /// - parameter code:     授权码
    /// - parameter finished: 加载成功的回调
    func loadUserAccessToken(code: String, finished: (isSuccessed:Bool) -> ()) {
        
        /// 调用网络工具,加载用户令牌
        NetworkTools.sharedTools.loadAccessToken(code) { (success, failure) -> () in
            
            if (failure != nil) {
                print(failure)
                finished(isSuccessed: false)
                return
            }
            
            /// 用户账号模型
            self.account = UserAccount(dict: success as! [String : AnyObject])
            
            /// 加载用户信息
            NetworkTools.sharedTools.loadUserInfo(self.account!.uid!, finished: { (success, failure) -> () in
                
                if failure != nil {
                    print("加载用户信息出错")
                    finished(isSuccessed: false)
                    return
                }
                
                guard let dict = success as? [String: AnyObject] else {
                    print("格式有误")
                    finished(isSuccessed: false)
                    return
                }
                
                self.account!.screenName = dict["screen_name"] as? String
                self.account!.avatarLarge = dict["avatar_large"] as? String
                
                /// 保存用户信息
                NSKeyedArchiver.archiveRootObject(self.account!, toFile: self.accountPath)
                
                finished(isSuccessed: true)
            })
        }

        
    }
    
}


